<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .doc-list {
    height: 48px;
    line-height: 16px;
    color: rgba(0, 0, 0, .54);
    font-weight: 500;
    display: flex;
    box-sizing: border-box;
    padding: 16px;
    align-items: center;
  }

  .arrow-sq {
    right: -25px;
    top: -20px;
    z-index: 10;
    width: 20px;
    height: 20px;
    color: #fff;
    text-size: 24px;
    line-height: 20px;
    text-align: center;
  }

  .el-tree-node {
    padding-left: 0px;
    margin: 10px 0;
  }
</style>
<template>
  <div id="filetree" class="pos-rlt">
    <h3 class="doc-list text-size-14">
      文档列表
      <i class="el-icon-circle-plus col-ff4 text-size-24 padder-l-10" @click="addFile"></i>
    </h3>
    <span class="pos-abt arrow-sq bg-ff4 border-radius-50 padder-v-15 cur-point"
          @click="toggleAside">&gt;</span>
    <el-tree :data="zNodes" :props="defaultProps" highlight-current @node-click="zTreeOnClick"
             :render-content="renderContent"></el-tree>
  </div>
</template>
<script>
  import Blog from '../assets/js/models/blog.model';
  import {Loading} from 'element-ui';

  export default {
    name: 'filetree',
    data () {
      return {
        filePath: 'filePath',
        addFilePath: '',
        zNodes: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        marginL: true,
        filename: '',
        cnst: {}
      }
    },
    methods: {
      toggleAside () {
        if (this.marginL) {
          $('.el-aside').animate({'marginLeft': '-300px'}, 500)
          this.marginL = false;
        } else {
          $('.el-aside').animate({'marginLeft': '0px'}, 500)
          this.marginL = true;
        }
      },
      addFileAjax (filename, data) {
        const date = filename.split('-')[0] + '-' + filename.split('-')[1] + '-' + filename.split('-')[2];
        const title = filename.split('-')[3];
        const _this = this;
        const datas = {
          label: filename + '.md',
          path: this.addFilePath,
          fileName: filename + '.md',
          isDir: 0,
          content: Blog.blogModel(title, date)
        }
        this.services.file.addFile(datas).then((d) => {
          if (!data.children) {
            _this.$set(data, 'children', []);
          }
          datas.href = this.addFilePath +'/' + filename + '.md';
          data.children.push(datas);
          _this.onHandleTab(d);
        })
      },
      getFileTree () {
        var _this = this;
        this.services.file.getFileTree(this.filePath).then((data) => {
          _this.zNodes = data;
        });
      },
      zTreeOnClick (data, Node, tree) {
        if (!data.expand) {
          this.onHandleTab(data);
        }
      },
      onHandleTab (treeNode) {
        this.path = treeNode.href;
        var _this = this;
        $.getJSON("/api/file/content", {
          path: _this.path
        }, function (data) {
          _this.$store.commit('setSelectedNode', treeNode);
          _this.$store.commit('setSelectedTitle', treeNode.label);
          _this.$store.commit('setSelectedNodeContent', data.resultData.content);
        });
      },
      addFile (data) {
        const h = this.$createElement;
        const _this = this;
        this.$msgbox({
          title: '新建文档',
          message: h('div', null, [
            h('span', null, '文件名(形如：2017-02-04-Hello)'),
            h('div', {class: 'el-input m-t-10'}, [
              h('input', {class: 'el-input__inner filename'}, '')
            ])
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              _this.addFileAjax($('.filename').val(), data);
              instance.confirmButtonLoading = false;
              done();
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'info',
            message: 'action: ' + action
          });
        });
      },

      remove (node, data) {
        var _this = this;
        this.services.file.deleteFile(data.href).then((datas) => {
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.$treeNodeId === data.$treeNodeId);
          children.splice(index, 1);
        });
      },
      renderContent: function (createElement, {node, data, store}) {
        var self = this;
        return createElement('span', [
          createElement('span', {
            attrs: {
              class: "text-size-13",
              title: node.label,
            }
          }, node.label.length > 20 ? node.label.substring(0, 20) + '...' : node.label),
          createElement('span', {
            attrs: {
              style: "z-index: 3; right: 10px;",
              class: "pos-abt pull-right m-r-0"
            }
          }, [
            createElement('i', {
              attrs: {
                class: "col-ff4 el-icon-circle-plus text-size-24",
                style: data.expand ? '' : 'display: none;'
              }, on: {
                click: function (event) {
                  event.stopPropagation();
                  self.addFilePath = data.href;
                  self.addFile(data);
                }
              }
            }),
            createElement('i', {
              attrs: {
                class: "col-ff4 el-icon-remove text-size-24",
//                style: data.expand ? 'display: none;' : ''
              }, on: {
                click: function (event) {
                  event.stopPropagation();
                  self.remove(node, data);
                }
              }
            })
          ]),
        ]);
      }
    },
    watch: {},
    created () {
      const _this = this;
      const data = eval('(' + localStorage.getItem('userModel') + ')');
      this.$store.commit('setUserModel', data);
      this.cnst = data;
      let loadingInstance1 = Loading.service({fullscreen: true, text: '初次加载，所需时间可能有点长，请耐心等候！'});
      this.services.git.login(data).then((data) => {
        _this.filePath = data;
        loadingInstance1.close();
        _this.getFileTree();
      })
    }
  }
</script>
